<?php


namespace App\Command\Changedata;

use App\Web\Model\Team;
use EchoPHP\Console\Command;
use EchoPHP\Facades\Db;

/**
 * 初始化团队名称，添加全名显示
 * Class InitTeamName
 * @package App\Command\Changedata
 */
class InitTeamName extends Command {
    protected $signature = "changedata:initTeamName";
    protected $description = '初始化团队名称';

    protected $delimiter = '*&*';

    public function handle() {
        $teamModel = new Team();
        $teamList = $teamModel->getWorkTeamList(null);

        /**
         * 初始化团队名称中的*&* 替换为***
         */
        $this->initName();

        $this->updateTeamFullName($teamList);

        $this->output->writeln('执行结束');
    }

    protected function initName() {
        //预处理，避免有团队名称中带分隔符的
        $sql = 'UPDATE Team SET teamname=REPLACE(teamname,?,?) ';
        $var = [$this->delimiter, '***'];
        $count = Db::connect()->update($sql, $var);
        $this->output->writeln('初始化团队名称完成，有' . $count . '条记录');
    }

    private function updateTeamFullName($teamList, $parentName = '') {
        foreach ($teamList as $item) {
            if (!empty($parentName)) {
                $fullName = $parentName . $this->delimiter . $item['teamname'];
            } else {
                $fullName = $item['teamname'];
            }
            $sql = 'UPDATE Team SET fullname=? WHERE teamid=?';
            $var = [$this->delimiter . $fullName . $this->delimiter, $item['teamid']];
            Db::connect()->update($sql, $var);
            $this->output->writeln('teamcode:[' . $item['teamcode'] . '];fullname:' . $fullName);

            if (isset($item['child']) && !empty($item['child'])) {
                $this->updateTeamFullName($item['child'], $fullName);
            }
        }
    }

}